import { useRef } from "react";
import { useHistory, useLocation } from "react-router-dom";
import { Button, Form, Input } from "antd";
import { LockOutlined, UserOutlined, FlagOutlined } from "@ant-design/icons";
import { useAppDispatch } from "@/hooks";

import Captcha from "./components/captcha.tsx";
import styled from "./index.module.css";
import { fetchLogin } from "@/store/features/user-slice.ts";

const Login = () => {
  // initialValues
  const initialValues = {
    username: "admin",
    password: "123456",
  };

  // 创建一个用于引用 Captcha 组件的 ref 数据
  const captchaRef = useRef<{ get: () => string; refresh: () => void }>(null);

  const dispatch = useAppDispatch();
  const history = useHistory();
  const { search } = useLocation();
  const searchParams = new URLSearchParams(search);

  const onFinish = async (values: any) => {
    // 获取 captchaId
    const captchaId = captchaRef.current?.get();

    try {
      // 直接派发动作
      await dispatch(fetchLogin({ ...values, captchaId })).unwrap();
      // dispatch 将错误给包裹了一层，导致没有错误, 可以在 dispatch 后面添加一个 unwrap()

      // 获取 search 参数
      const redirect = searchParams.get("redirect") || "/";
      // 跳转页面
      history.replace(redirect);
    } catch (e) {
      // 操作 Captcha 组件 刷新 验证码
      captchaRef.current?.refresh();
    }

    // 调用登录接口
    // login({
    //   ...values,
    //   captchaId,
    // })
    //   .then((resp) => {
    //     console.log("then", resp);
    //     // 操作储存一下
    //     store2.set("token", resp.token);
    //     store2.set("expire", resp.expire);
    //     store2.set("refreshToken", resp.refreshToken);
    //     store2.set("refreshExpire", resp.refreshExpire);
    //     // 派发登录动作
    //     dispatch({ type: "LOGIN", payload: resp });
    //     // 获取 search 参数
    //     const redirect = searchParams.get("redirect") || "/";
    //     // 跳转页面
    //     history.replace(redirect);
    //   })
    //   .catch(() => {
    //     // 操作 Captcha 组件 刷新 验证码
    //     captchaRef.current?.refresh();
    //   });
  };

  return (
    <div className={styled.page}>
      <h2>登录</h2>
      <Form
        className={styled.form}
        validateTrigger="onBlur"
        initialValues={initialValues}
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: "必须" }]}
        >
          <Input prefix={<UserOutlined />} placeholder="Username" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: "必须" }]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="Password" />
        </Form.Item>

        <Form.Item
          name="verifyCode"
          rules={[{ required: true, message: "必须" }]}
        >
          <div style={{ display: "flex" }}>
            <Input prefix={<FlagOutlined />} placeholder="VerifyCode" />
            <Captcha ref={captchaRef} />
          </div>
        </Form.Item>

        <Form.Item>
          <Button block type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
